package home.google.apps.server;

import home.google.apps.client.Entry;
import home.google.apps.client.PersistentEntryService;

import java.util.List;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;

@SuppressWarnings("serial")
public class PersistentEntryServiceImpl extends RemoteServiceServlet implements
		PersistentEntryService {

	private static Objectify getService() {
		return ObjectifyService.begin();
	}

	static {
		ObjectifyService.register(Entry.class);
	}

	@Override
	public void persistEntry(String name, String phone) {
		Objectify ofy = getService();
		Entry entry = new Entry();
		entry.setFullName(name);
		entry.setPhoneNumber(phone);
		ofy.put(entry);

		assert entry.getId() != null; // id was autogenerated

		// Get it back
		System.out.println("id = " + entry.getId());
	}

	@Override
	public void deleteEntry(Entry entry) {
		Objectify ofy = getService();
		ofy.delete(entry);
	}

	@Override
	public String findByName(String name) {
		Objectify ofy = getService();
		Entry e = null;
		e = ofy.query(Entry.class).filter("FullName", name).get();
		
		if (e != null)
			return e.toString();
		else
			return "This entry corresponding to "+name+" does not exist";						
	}

	public List<Entry> findAllEntries() {
		Objectify ofy = getService();
		List<Entry> entries = ofy.query(Entry.class).list();
		return entries;
	}

	@Override
	public Entry getByName(String name) {
		Objectify ofy = getService();
		Entry e = ofy.query(Entry.class).filter("FullName", name).get();
		
		return e;
	}

}
